#include "qt_helper.h"

#include <QMessageBox>
#include <QFileDialog>

#include <util/gref.h>

namespace util {

QtHelper::QtHelper(QObject * pParent_)
: QObject(pParent_)
{
}



void QtHelper::SetIconSize(int W_, int H_)
{
  mIconSize = QSize(W_, H_);
}

QObject * QtHelper::MakeToolBar(QMainWindow * pParent_, const QString & ID_, const QString & Title_)
{
  QToolBar * pToolBar = new QToolBar(Title_, pParent_);
  pToolBar->setObjectName(ID_);
  pParent_->addToolBar(Qt::TopToolBarArea, pToolBar);
  pToolBar->setIconSize(mIconSize);

  return pToolBar;
}

QObject *QtHelper::MakeMenuBar(QMainWindow * pParent_, const QString & ID_)
{
  QMenuBar * pMenuBar = new QMenuBar(pParent_);
  pMenuBar->setObjectName(ID_);
  pParent_->setMenuBar(pMenuBar);

  return pMenuBar;
}

QObject *QtHelper::AddMenu(QWidget * pWidget_, const QString & ID_, const QString & Title_)
{
  QMenu * pMenu = new QMenu(pWidget_);

  pMenu->setObjectName(ID_);
  pMenu->setTitle(Title_);

  pWidget_->addAction(pMenu->menuAction());

  return pMenu;
}

void QtHelper::AddActions(QWidget * pWidget_, const QObjectList &Actions_)
{
  foreach (QObject *pActionObject, Actions_)
  {
    QAction * pAction = qobject_cast<QAction *>(pActionObject);

    if (pAction)
      pWidget_->addAction(pAction);
    else
    {
      QMenu * pMenu = qobject_cast<QMenu *>(pWidget_);

      if (pMenu)
        pMenu->addSeparator();
      else
      {
        QToolBar * pToolBar = qobject_cast<QToolBar *>(pWidget_);

        if (pToolBar)
          pToolBar->addSeparator();
      }
    }
  }
}

void QtHelper::MessageBoxAbout(QWidget *pParent_, const QString & Title_, const QString & Text_)
{
  QMessageBox::about(pParent_, Title_, Text_);
}

void QtHelper::GetOpenFileName(QWidget * pParent_, const QString & Caption_, const QString & Dir_, const QStringList & Filters_, QScriptValue ret)
{
  QString filter = "";
  foreach (const QString & filterString, Filters_)
    filter += filterString + ";;";

  QString selectedFilter;
  QString fileName = QFileDialog::getOpenFileName(pParent_, Caption_, Dir_, filter, &selectedFilter);

  ret.setProperty("FileName", fileName);
  ret.setProperty("FilterIndex", Filters_.indexOf(selectedFilter));
}

} // namespace util {